﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace ERP.WebUI
{
    public class UserRepository 
    {
        private EFDbContext db = new EFDbContext();
        public IQueryable<User> Users
        {
            get { return db.Users; }
        }

        public OperationResult Insert(UserModel model)
        {
            var entity = new User
            {
                LoginName = model.LoginName,
                LoginPwd = DESProvider.EncryptString(model.NewLoginPwd),
                FullName = model.FullName,
                Email = model.Email,
                Phone = model.Phone,
                Enabled = model.Enabled,
                PwdErrorCount = 0,
                LoginCount = 0,
                RegisterTime = DateTime.Now,
                CreateId = model.CreateId,
                CreateBy = model.CreateBy,
                CreateTime = DateTime.Now,
                ModifyId = model.ModifyId,
                ModifyBy = model.ModifyBy,
                ModifyTime = DateTime.Now
            };

            #region Add User Role Mapping
            RoleRepository roleRepository = new RoleRepository();
            foreach (int roleId in model.SelectedRoleList)
            {
                if (roleRepository.Roles.Any(t => t.Id == roleId))
                {
                    entity.UserRole.Add(
                        new UserRole()
                        {
                            User = entity,
                            RoleId = roleId,
                            CreateId = model.CreateId,
                            CreateBy = model.CreateBy,
                            CreateTime = DateTime.Now,
                            ModifyId = model.ModifyId,
                            ModifyBy = model.ModifyBy,
                            ModifyTime = DateTime.Now
                        });
                }
            }

            #endregion

            db.Entry<User>(entity).State = EntityState.Added;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "添加成功");
        }

        /// <summary>
        /// 更新登录信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Update(User model)
        {
            db.Set<User>().Attach(model);
            db.Entry<User>(model).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success);
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Update(UpdateUserModel model)
        {
            var entity = Users.FirstOrDefault(t => t.Id == model.Id);

            entity.FullName = model.FullName;
            entity.Phone = model.Phone;
            entity.Enabled = model.Enabled;
            entity.ModifyId = model.ModifyId;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;

            #region Update User Role Mapping
            UserRoleRepository userRoleRepository = new UserRoleRepository();
            var oldRoleIds = userRoleRepository.UserRoles.Where(t => t.IsDeleted == false && t.UserId == model.Id).Select(t => t.RoleId).ToList();
            var newRoleIds = model.SelectedRoleList.ToList();
            var intersectRoleIds = oldRoleIds.Intersect(newRoleIds).ToList(); // Same Ids
            var removeIds = oldRoleIds.Except(intersectRoleIds).ToList(); // Remove Ids
            var addIds = newRoleIds.Except(intersectRoleIds).ToList(); // Add Ids
            foreach (var removeId in removeIds)
            {
                //更新状态
                userRoleRepository = new UserRoleRepository();
                var userRole = userRoleRepository.UserRoles.FirstOrDefault(t => t.UserId == model.Id && t.RoleId == removeId);
                userRole.IsDeleted = true;
                userRole.ModifyId = model.ModifyId;
                userRole.ModifyBy = model.ModifyBy;
                userRole.ModifyTime = DateTime.Now;

                userRoleRepository.Update(userRole);
            }
            foreach (var addId in addIds)
            {
                userRoleRepository = new UserRoleRepository();
                var userRole = userRoleRepository.UserRoles.FirstOrDefault(t => t.UserId == model.Id && t.RoleId == addId);
                // 已有该记录，更新状态
                if (userRole != null)
                {
                    userRole.IsDeleted = false;
                    userRole.ModifyId = model.ModifyId;
                    userRole.ModifyBy = model.ModifyBy;
                    userRole.ModifyTime = DateTime.Now;
                    userRoleRepository.Update(userRole);
                }
                // 插入
                else
                {
                    entity.UserRole.Add(new UserRole
                    {
                        UserId = model.Id,
                        RoleId = addId,
                        CreateId = model.CreateId,
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        ModifyId = model.ModifyId,
                        ModifyBy = model.ModifyBy,
                        ModifyTime = DateTime.Now
                    });
                }
            }

            #endregion

            db.Set<User>().Attach(entity);
            db.Entry<User>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "更新成功");
        }

        public OperationResult Delete(UserModel model)
        {
            var entity = Users.FirstOrDefault(t => t.Id == model.Id);
            entity.IsDeleted = true;
            entity.ModifyId = model.ModifyId;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;

            db.Set<User>().Attach(entity);
            db.Entry<User>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "删除成功");
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public User CheckUserLogin(Expression<Func<User, bool>> whereLambda)
        {
            return db.Users.Where(whereLambda).FirstOrDefault();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Update(ChangePwdModel model)
        {
            var entity = Users.FirstOrDefault(t => t.Id == model.Id);
            entity.LoginPwd = DESProvider.EncryptString(model.NewLoginPwd);
            entity.ModifyId = model.ModifyId;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;

            db.Set<User>().Attach(entity);
            db.Entry<User>(entity).State = EntityState.Modified;
            db.SaveChanges();
            return new OperationResult(OperationResultType.Success, "修改密码成功");
        }
    }
}